package
{       
	import as3isolib.core.IIsoDisplayObject;
	import as3isolib.display.IsoSprite;
	import as3isolib.display.IsoView;
	import as3isolib.display.primitive.IsoBox;
	import as3isolib.display.primitive.IsoRectangle;
	import as3isolib.display.scene.IsoGrid;
	import as3isolib.display.scene.IsoScene;
	import as3isolib.enum.IsoOrientation;
	import as3isolib.geom.IsoMath;
	import as3isolib.geom.Pt;
	import as3isolib.graphics.BitmapFill;
	import as3isolib.graphics.IStroke;
	import as3isolib.graphics.SolidColorFill;
	import as3isolib.graphics.Stroke;
	
	import com.adobe.serialization.json.JSON;
	import com.facebook.graph.Facebook;
	import com.gskinner.motion.GTween;
	
	import eDpLib.events.ProxyEvent;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Graphics;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.PixelSnapping;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.filters.*;
	import flash.filters.BitmapFilterQuality;
	import flash.filters.GlowFilter;
	import flash.geom.ColorTransform;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;
	import flash.text.AntiAliasType;
	import flash.text.Font;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;
	import flash.utils.Timer;
	
	import flashx.textLayout.tlf_internal;
	
	import mx.core.BitmapAsset;
	
	public class Render extends Sprite
	{
		protected static const APP_ID:String = "591843377498647"; //do not change
		public static const debug:Boolean = false;
		
		private static var fps:int = 60;
		public static var engine:Engine;
		public static var SCR_WID : int = 1280;
		public static var SCR_HGT : int = 720;
		public static var gridSize:int = 10;
		public static var gridWidth:int = 100;
		
		public var currentWorkingX : int = 0;
		public var currentWorkingY : int = 0;
		
		//subwindows
		public var garageWindow:garageSubWindow;
		public var carShow:CarShow ;
		
		//IMAGES
		private var build:ImageSprite = new ImageSprite();
		private var cancelBuild:ImageSprite = new ImageSprite();
		private var race:ImageSprite = new ImageSprite();
		private var alert1:AlertButton = new AlertButton();
		private var zoomblock:ImageSprite = new ImageSprite();
		private var zoombar:ImageSprite = new ImageSprite();
		private var carshowImage:ImageSprite = new ImageSprite();
		//building images
		private var garage:ImageSprite = new ImageSprite();
		private var powerFarm:ImageSprite = new ImageSprite();
		private var factory:ImageSprite = new ImageSprite();
		private var silo:ImageSprite = new ImageSprite();
		
		private var garageAn:Animation = new Animation();
		private var powerFarmAn:Animation = new Animation();
		private var factoryAn:Animation = new Animation();
		private var siloAn:Animation = new Animation();
		
		private var silos:Array = new Array();
		
		//RENDER SHIT
		public var scene:IsoScene;
		private var panPt:Point;
		private var view:IsoView = new IsoView();
		private var zoom:Number = 0.5;
		private var g:IsoGrid = new IsoGrid();
		private var gridRect:Array = new Array();
		
		private var tempDrag:IsoSprite = new IsoSprite();
		private var dragX:int=-1;
		private var dragY:int=-1;
		
		
		//GUI SHIT
		private var grass:ImageSprite = new ImageSprite();
		private var myImgLoader:Loader;
		
		private var menu:Menu = new Menu();
		private var garageMenu:upMenu = new upMenu();
		private var generatorMenu:upMenu = new upMenu();
		private var factoryMenu:upMenu = new upMenu();
		
		private var garageChooseMenu:slideMenu = new slideMenu();
		private var goldAmount:Number = 900;
		private var maxGoldAmount:int = 1000;
		private var fuelAmount:int = 100;
		private var maxFuelAmount:int = 1000;
		public var expAmount:int = 0;
		public var maxExpAmount:int = 100;
		public var level:int = 1;
		private var lowZoom:Number = 0.3;
		private var highZoom:Number = 1.7 ;
		private var zoomBarX : Number = SCR_WID-40;
		private var zoomBarY : Number = 150;
		
		//Sounds
		private var gameSound:Player = new Player();
		private var placement:Player = new Player();
		private var garageClick:Player = new Player();
		public static var factoryPlace:Player = new Player();
		public static var factoryLoop:Player = new Player();
		public static var GeneratorPlace:Player = new Player();
		public static var GeneratorLoop:Player = new Player();
		public var upgradeSound:Player = new Player();
		private var spendCoin:Player = new Player();
		private var collectCoin:Player = new Player();
		private var collectFuel:Player = new Player();
		private var errorSound:Player = new Player();
		public var openMenuWoosh:Player = new Player();
		public var closeMenuWoosh:Player = new Player();
		private var openMenu:Player = new Player();
		private var closeMenu:Player = new Player();
		
		//GLOBAL SHIT
		private var building:Boolean = false;
		private var prebuild:Boolean = false;
		private var buildType:String;
		private var currentBuilding:ImageSprite = new ImageSprite();
		
		public var garageButt:Button;
		public var generatorButt:Button;
		public var factoryButt:Button;
		public var siloButt:Button;
		
		private var bg:ImageSprite = new ImageSprite();
		private var bgtile:ImageSprite = new ImageSprite();
		private var tileBG:Sprite;
		
		public function Render (){
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.stageHeight = Render.SCR_HGT;
			stage.stageWidth = Render.SCR_WID;
			stage.align = StageAlign.TOP_LEFT;
			
			
			placement.load("assets/sounds/Placement.mp3");
			gameSound.load("assets/sounds/Background Noise.mp3");
			gameSound.loopNow=true;
			garageClick.load("assets/sounds/Garage/Garage 1.mp3");
			factoryPlace.load("assets/sounds/Factory/Factory.mp3");
			factoryLoop.load("assets/sounds/Factory/Factory Loop.mp3");
			GeneratorPlace.load("assets/sounds/Generator/Generator.mp3");
			GeneratorLoop.load("assets/sounds/Generator/Generator Loop.mp3");
			spendCoin.load("assets/sounds/Money/Spend.mp3");
			collectCoin.load("assets/sounds/Money/Collect.mp3");
			collectFuel.load("assets/sounds/Fuel/Collect.mp3");
			upgradeSound.load("assets/sounds/Upgrade.mp3");
			errorSound.load("assets/sounds/Menu/No.mp3");
			openMenu.load("assets/sounds/Menu/Open Menu.mp3");
			closeMenu.load("assets/sounds/Menu/Close Menu.mp3");
			openMenuWoosh.load("assets/sounds/Menu/Open Menu Slide.mp3");
			closeMenuWoosh.load("assets/sounds/Menu/Close Menu Slide.mp3");
			
			
			garageWindow = new garageSubWindow(this);
			carShow= new CarShow(this);
			carShow.loadCars();
			//cacheAsBitmap = true;
			this.addEventListener(MouseEvent.MOUSE_MOVE,buildDragEffect);
			Formatting.setup();
			tileBG = new Sprite();
			tileBG.graphics.beginFill(0x0A6BB7);
			tileBG.graphics.drawRect(0,0,1280,720);
			tileBG.graphics.endFill();
			addChild(tileBG);
			
			bg.overrideSize(4445,2500);
			bg.load(null, "assets/images/bgOcean.jpg");
			bg.x = -2100;
			bg.y = -675;
			view.backgroundContainer.addChild(bg);
			
			renderScene();
			renderGUI();
			if(debug){
				playerText = Formatting.newTitle("name", 0xFFFFFF, 5, 16, 200, 50);
				addChild(playerText);
			} else Facebook.init(APP_ID, initFB);
			var myTimer:Timer = new Timer(1000/15); // 1 second
			myTimer.addEventListener(TimerEvent.TIMER, updateGUI);
			myTimer.start();
			engine = new Engine(this);
		}
		
		private function initFB(result:Object, fail:Object):void{
			if (result) { //already logged in
				Facebook.api("/me", setPlayerName, null, "GET");
			} else {
				var opts:Object = {scope:"publish_stream, user_photos"};
				Facebook.login(onLogin, opts);
			}
		}
		
		protected function onLogin(result:Object, fail:Object):void {
			if (result) { //successfully logged in
				trace("Logged In");
				//get player name
				Facebook.api("/me", setPlayerName, null, "GET");
			} else {
				trace("Login Failed");				
			}
		}
		
		private function setPlayerName(result:Object, fail:Object):void{
			playerText = Formatting.newTitle(result["name"], 0xFFFFFF, 5, 16, 200, 50);
			addChild(playerText);
		}
		
		/*public function setupBG():void{
			tileBG.graphics.beginFill(0x0A6BB7); // beginBitmapFill(bgtile.bitmap);
			tileBG.graphics.drawRect(0,0,stage.stageWidth,stage.stageHeight);
			tileBG.graphics.endFill();
		}*/
		
		public function renderGUI():void{
			
			setupGUIBars();
			
			//load images
			//load zoom images
			
			zoombar.overrideSize(32,0);
			zoombar.setPosition(zoomBarX,zoomBarY);
			addChild(zoombar);
			zoombar.load(null,"assets/images/zoombar.png");
			
			zoomblock.load(this,"assets/images/zoomblock.png");
			zoomblock.setPosition(zoomBarX-13,zoomBarY+100);
			zoomblock.addEventListener(MouseEvent.MOUSE_DOWN,dragMouseDown );
			
			//load build image
			build.addEventListener(MouseEvent.CLICK, beginBuild);
			build.setPosition(25, SCR_HGT-75+1);
			build.overrideSize(75,50);
			build.load(this,"assets/images/build.png");
			build.filters = [ new DropShadowFilter()];
			//load cancel build
			cancelBuild.addEventListener(MouseEvent.CLICK,cancelBuilding);
			cancelBuild.setPosition(100, SCR_HGT-75+1);
			cancelBuild.overrideSize(50,0);
			cancelBuild.load(this,"assets/images/HUD_Cancel.png");
			cancelBuild.visible=false;
			//load race image
			race.addEventListener(MouseEvent.CLICK, beginRace);
			race.setPosition(SCR_WID-75, SCR_HGT-75+1);
			race.overrideSize(75,50);
			race.load(this,"assets/images/HUD_Race.png");
			//load showcar image
			carshowImage.addEventListener(MouseEvent.CLICK, carshowBegin);
			carshowImage.setPosition(SCR_WID-155, SCR_HGT-75+1);
			carshowImage.overrideSize(75,50);
			carshowImage.load(this,"assets/images/gui/HUD_CarShow.png");
			//load alert1 image
			alert1.setPosition(SCR_WID/2, SCR_HGT/2+1);
			alert1.overrideSize(75,50);
			alert1.visible=false;
			alert1.load(this,"assets/images/HUD_Alert1.png");
			
			//CREATE MENU
			menu.giveRender(this);
			menu.setPosition(0, SCR_HGT-220);
			//addChild(menu);
			
			if(debug){
				generatorButt = menu.add("assets/images/powerFarmSel.png");
				siloButt = menu.add("assets/images/siloSel.png");
				factoryButt = menu.add("assets/images/factorySel.png");
				garageButt = menu.add("assets/images/garageSel.png");
				goldAmount=maxGoldAmount;
			}else{
				garageButt = menu.add("assets/images/garageSel.png",true);
				factoryButt = menu.add("assets/images/factorySel.png");
				generatorButt = menu.add("assets/images/powerFarmSel.png",true);
				siloButt = menu.add("assets/images/siloSel.png", true);
			}
			//engine.addExp(0);
			/*menu.add("assets/images/garageSel.png");
			menu.add("assets/images/powerFarmSel.png");
			menu.add("assets/images/factorySel.png");*/
			
			garageMenu.giveRender(this);
			garageMenu.setPosition(SCR_WID/2, SCR_HGT-200);
			garageMenu.giveBackground("assets/images/gui/HUD_GradBox.png",300);
			garageMenu.add("assets/images/gui/Garage_Button.png");
			garageMenu.add("assets/images/gui/Collect_Coin_Button.png",true);
			garageMenu.add("assets/images/gui/Upgrade_Button.png");
			
			generatorMenu.giveRender(this);
			generatorMenu.setPosition(SCR_WID/2, SCR_HGT-200);
			generatorMenu.giveBackground("assets/images/gui/HUD_GradBox.png",300);
			generatorMenu.add("assets/images/gui/Collect_Fuel_Button.png",true);
			generatorMenu.add("assets/images/gui/Upgrade_Button.png");
			
			factoryMenu.giveRender(this);
			factoryMenu.setPosition(SCR_WID/2, SCR_HGT-200);
			factoryMenu.giveBackground("assets/images/gui/HUD_GradBox.png",300);
			factoryMenu.add("assets/images/gui/Create_Car.png");
			factoryMenu.add("assets/images/gui/Upgrade_Button.png");
			
		
			
			garageChooseMenu.giveRender(this);
			garageChooseMenu.setPosition(70,100);
			garageChooseMenu.addMany("assets/images/gui/HUD_GradBox.png",6);

			
			
			scene.render();
			scene.layoutEnabled = false;
			
			//engine remove child x|y lower, add to map, move back
		}
		
		private var playerText:TextField = null;
		public var lvlText:TextField;
		private var expImgFill : ImageSprite;
		private var goldText:TextField;
		private var goldImgFill : ImageSprite;
		private var fuelText:TextField;
		private var fuelImgFill : ImageSprite;
		private function setupGUIBars():void{
			//GOLD
			goldImgFill = new ImageSprite();
			var size : int = goldAmount/maxGoldAmount*140 + 1;
			goldImgFill.setPosition(SCR_WID-145 + 140-size,17);
			goldImgFill.load(null,"assets/images/gui/goldFillSmall.png");
			addChild(goldImgFill);
			
			var goldImg:ImageSprite = new ImageSprite();
			goldImg.setPosition(SCR_WID-185,10);
			goldImg.load(null,"assets/images/gui/goldBottomSmall.png");
			addChild(goldImg);
			
			var goldImgTop : ImageSprite = new ImageSprite();
			goldImgTop.setPosition(SCR_WID-185,10);
			goldImgTop.load(null,"assets/images/gui/goldTopSmall.png");
			addChild(goldImgTop);
			
			goldText = Formatting.newTitle(goldAmount+"", 0xFFFFFF, SCR_WID-110, 19, 105, 50);
			addChild(goldText);
			
			//FUEL
			fuelImgFill = new ImageSprite();
			size = fuelAmount/maxFuelAmount*140 + 1;
			fuelImgFill.setPosition(SCR_WID-145 + 140-size,78);
			fuelImgFill.load(null,"assets/images/gui/fuelFillSmall.png");
			addChild(fuelImgFill);
			
			var fuelImg:ImageSprite = new ImageSprite();
			fuelImg.setPosition(SCR_WID-178,61);
			fuelImg.load(null,"assets/images/gui/fuelBottomSmall.png");
			addChild(fuelImg);
			
			var fuelImgTop : ImageSprite = new ImageSprite();
			fuelImgTop.setPosition(SCR_WID-178,61);
			fuelImgTop.load(null,"assets/images/gui/fuelTopSmall.png");
			addChild(fuelImgTop);
			
			fuelText = Formatting.newTitle(fuelAmount+"", 0xFFFFFF, SCR_WID-110, 80, 105, 50);
			addChild(fuelText);
			
			//EXP BAR
			expImgFill = new ImageSprite();
			size = expAmount/maxExpAmount*180;
			expImgFill.setPosition(6,51);	//(6 + 180-size,51)
			expImgFill.load(null,"assets/images/gui/userLevelFillSmall.png");
			addChild(expImgFill);
			
			var expImg:ImageSprite = new ImageSprite();
			expImg.setPosition(5,50);
			expImg.load(null,"assets/images/gui/userLevelBottomSmall.png");
			addChild(expImg);
			
			var expImgTop : ImageSprite = new ImageSprite();
			expImgTop.setPosition(5,50);
			expImgTop.load(null,"assets/images/gui/userLevelTopSmall.png");
			addChild(expImgTop);
			
			//if(playerText == null) playerText = Formatting.newTitle("Zhou Fang", 0xFFFFFF, 5, 16, 200, 50);
			//addChild(playerText);
			
			lvlText = Formatting.newSubtitle("LEVEL "+level, 0xFFFFFF, 14, 56, 200, 50);
			addChild(lvlText);
		}
		
		public function updateGUI(e:Event):void{
			engine.calcEarnedResources();
			
			//gold
			var size : int = goldAmount/maxGoldAmount*140 + 1;
			goldImgFill.resizeCertain(size, 34);
			goldImgFill.setPosition(SCR_WID-145 + 140-size,17);
			goldText.text=""+int(goldAmount);
			
			//fuel
			size = fuelAmount/maxFuelAmount*140 + 1;
			fuelImgFill.resizeCertain(size, 34);
			fuelImgFill.setPosition(SCR_WID-145 + 140-size,78);
			fuelText.text=""+fuelAmount;
			
			for each (var s:Building in silos){
				var v : Number = fuelAmount*10.0/maxFuelAmount;
				if (v==int(v))v=int(v);
				else v=int(v)+1;
				if(s!=null) s.image.setSprite(v);
			}
			
			
			//exp
			size = expAmount/maxExpAmount*180;
			if(size<1) size = 1;
			expImgFill.resizeCertain(size, 34);
			expImgFill.setPosition(6,51);
			
			//zoom 
			view.currentZoom = (highZoom-(zoomblock.y-zoomBarY+10)/(zoombar.hgt)*(highZoom-lowZoom));
			zoom = view.currentZoom;
			scene.render();
			engine.updateProgressLayer();
			
			
		}
		public function newAnimation(st:String,ratio:int,slides:int):Animation{
			var an:Animation = new Animation();
			an.overrideSize(gridWidth*ratio,gridWidth*ratio);
			an.initiate(st,slides);  
			return an;
		}
		public function renderScene():void{
			
			//load buildings images
			var gm:int = 3;
			var pm:int = 4;
			var fm:int = 5;
			garageAn.overrideSize(gridWidth*gm,gridWidth*gm);
			powerFarmAn.overrideSize(gridWidth*pm,gridWidth*pm);
			factoryAn.overrideSize(gridWidth*fm,gridWidth*fm);
			siloAn.overrideSize(gridWidth*2,gridWidth*2);
			garageAn = newAnimation("GarageAnimation",gm,1);
			powerFarmAn= newAnimation("GeneratorAnimation",pm,7);
			factoryAn = newAnimation("FactoryAnimation",fm,23);
			siloAn = newAnimation("SiloAnimation",2,10);
			
			
			
			g.showOrigin=false;
			scene = new IsoScene();
			g.cellSize = gridWidth;
			g.setGridSize(gridSize,gridSize,0);
			g.autoUpdate = true;
			scene.addChild(g);
			
			//create ground			
			loadGrass("assets/images/tileable.png");
			
			
			//set view
			//view.clipContent = true;
			view.setSize(SCR_WID, SCR_HGT);
			view.zoom(zoom);
			view.currentZoom = zoom;
			view.addScene(scene);
			addChild(view);
			view.addEventListener(MouseEvent.CLICK, viewMouseClick);
			view.addEventListener(MouseEvent.MOUSE_DOWN, viewMouseDown);
			//REMOVED ZOOM WHEEL FOR NOW
			//view.addEventListener(MouseEvent.MOUSE_WHEEL, viewZoom);
			view.panTo(0,300);
			
		}
		
		private function loadGrass(url:String):void{
			var s : Stroke = new Stroke(1,0x008F00,0.1,false,"normal",null,null,0);
			for(var i:int = 0; i < gridSize; i++){
				for(var j:int = 0; j < gridSize; j++){
					var rect : IsoRectangle = new IsoRectangle();
					rect.strokes = [s];
					rect.setSize(gridWidth,gridWidth,0);
					rect.moveTo(i*gridWidth, j*gridWidth, 0);
					scene.addChild(rect);
					gridRect.push(rect);	
				}
			}
			var loader : Loader = new Loader();
			loader.load(new URLRequest(url), new LoaderContext(true));
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, imgLoadComplete);
		}
		
		private function imgLoadComplete(e:Event):void
		{
			if(e.target.url.toString().substr(e.target.url.toString().length-12) == "tileable.png"){
				/*var myImg:Bitmap = new Bitmap(e.target.content.bitmapData);
				var scale:Number = gridWidth/myImg.width;
				var matrix:Matrix = new Matrix();
				matrix.scale(scale, scale);
				var smallBMD:BitmapData = new BitmapData(myImg.width * scale, myImg.height * scale, true, 0x000000);
				smallBMD.draw(myImg, matrix, null, null, null, true);
				myImg = new Bitmap(smallBMD, PixelSnapping.NEVER, true);*/
				var f:SolidColorFill = new SolidColorFill(0,0);
				for(var i:int = 0; i < gridSize; i++){
					for(var j:int = 0; j < gridSize; j++){
						//gridRect[i*gridSize+j].fills = [new BitmapFill(myImg, IsoOrientation.XY)];
						gridRect[i*gridSize+j].fills = [f];
					}
				}
			} 
			scene.render();
		}
		
		private function beginRace(e:MouseEvent):void{
				var method:String = '{"message" : "Message!", "picture": "http://fbrell.com/f8.jpg", "name": "Motor City", "caption":"Hyphen Interactive", "description":"'+playerText.text+' just built his dream car!"}';
				var data:Object = {};
				try {
					data = com.adobe.serialization.json.JSON.decode(method);
				} catch (e:Error) {
					trace("\n\nERROR DECODING JSON: " + e.toString());
				}
				Facebook.ui("feed", data, null);
		}
		private function carshowBegin(e:Event):void{
			if (!carShow.showing)carShow.show();
			else carShow.hide();
		}
		
		private function beginBuild(e:MouseEvent):void{
			if (prebuild){
				prebuild=false;
				menu.hide();
				closeMenu.play();
				scene.render();
				return;
			}
			prebuild = true;
			menu.show();
			openMenu.play();
			scene.render();
		}
		
		public function command(i:String):void{
			
			i=i.substr(i.lastIndexOf("/")+1,i.length);
			trace(i);
			if (i=="Garage_Button.png"){
				garageClick.play();
				//garageWindow.show(currentWorkingX,currentWorkingY);
				garageChooseMenu.show();
			}
			else if (i=="Collect_Coin_Button.png" || i=="Collect_Fuel_Button.png"){
				var type : String = engine.getType(currentWorkingX, currentWorkingY);
				var resource : int = engine.getResourcesFromBuilding(currentWorkingX, currentWorkingY);
				engine.addExp(int(resource/5));
				var pt : PopupText;
				if(type == CONSTANTS.garageType){
					goldAmount += resource;
					if(goldAmount > maxGoldAmount) goldAmount = maxGoldAmount;
					pt = new PopupText(engine, "+"+resource, 0xE0C000, currentWorkingX, currentWorkingY);
					collectCoin.play();
				} else if(type == CONSTANTS.generatorType){
					fuelAmount += resource;
					if(fuelAmount > maxFuelAmount) fuelAmount = maxFuelAmount;
					pt = new PopupText(engine, "+"+resource, 0x00FF00, currentWorkingX, currentWorkingY);
					collectFuel.play();
				} else return;
			}
			else if(i=="Upgrade_Button.png"){
				if(fuelAmount < 200){
					errorSound.play();
					createAlert("Need 200 fuel to upgrade!");
				} else {
					fuelAmount -= 200;
					engine.levelUp(currentWorkingX,currentWorkingY);
				}
			}
			else if (i=="Create_Car.png"){
				engine.createCar();
			}
		}
		
		public function buildingChosen(i:String):void{
			cancelBuild.visible=true;
			prebuild=false;
			menu.hide();
			closeMenu.play();
			building=true;
			buildType=i;
			var ind:int = buildType.lastIndexOf("/");
			buildType = buildType.substr(ind+1,buildType.length);
			if (buildType == CONSTANTS.garageType){
				if (!engine.checkEnoughResources("Garage",goldAmount)){
					building = false;
					createAlert("Need 300 gold for this,\n build another car!");
					cancelBuild.visible=false;
					errorSound.play();
				}
				currentBuilding.bitmap = garage.bitmap;
			}
			else if (buildType == CONSTANTS.generatorType){
				currentBuilding.bitmap = powerFarm.bitmap;
				if (!engine.checkEnoughResources("powerFarm",goldAmount)){
					building = false;
					createAlert("Need 400 gold for this,\n build another car!");
					cancelBuild.visible=false;
					errorSound.play();
				}
			}
			else if (buildType == CONSTANTS.factoryType){
				if (!engine.checkEnoughResources("Factory",goldAmount)){
					building = false;
					createAlert("Need 500 gold for this,\n build another car!");
					cancelBuild.visible=false;
					errorSound.play();
				}
				currentBuilding.bitmap = factory.bitmap;
			}
			else if (buildType == CONSTANTS.siloType){
				if (!engine.checkEnoughResources("Silo",goldAmount)){
					building = false;
					createAlert("Need 200 gold for this,\n build another car!");
					cancelBuild.visible=false;
					errorSound.play();
				}
				currentBuilding.bitmap = silo.bitmap;
			}
		}
		
		private function createAlert(str:String):void{
			alert1.showAlert(str);
		}
		
		private function place(x:int,y:int):void{
			if (!engine.canPlace(buildType,x,y)){
				trace("Cannot place this there.");
				return;
			}
			var buildingSprite:Animation = new Animation();
			// DO FIXES TO POSITION! 
			var xfix:int = 0;
			var yfix:int = 0;
			var productionRate:Number = 0;
			var animated:Boolean = true;
			if (buildType==CONSTANTS.garageType){
				xfix=CONSTANTS.garagexfix; yfix=CONSTANTS.garageyfix;
				//money
				goldAmount -= CONSTANTS.garageCost;
				new PopupText(engine, "-"+CONSTANTS.garageCost, 0xE0C000, currentWorkingX, currentWorkingY);
				buildingSprite.pics = garageAn.pics;
				//engine.giveCar(x,y);
				productionRate = 3;
				animated=false;
			}
			else if (buildType==CONSTANTS.generatorType){
				xfix=CONSTANTS.generatorxfix; yfix=CONSTANTS.generatoryfix;
				goldAmount -= CONSTANTS.generatorCost;
				new PopupText(engine, "-"+CONSTANTS.generatorCost, 0xE0C000, currentWorkingX, currentWorkingY);
				buildingSprite.pics = powerFarmAn.pics;
				productionRate = 2;
			}
			else if (buildType==CONSTANTS.factoryType){
				xfix=CONSTANTS.factoryxfix; yfix=CONSTANTS.factoryyfix;
				goldAmount -= CONSTANTS.factoryCost;
				new PopupText(engine, "-"+CONSTANTS.factoryCost, 0xE0C000, currentWorkingX, currentWorkingY);
				buildingSprite.pics = factoryAn.pics;
			}
			else if (buildType==CONSTANTS.siloType){
				xfix=CONSTANTS.siloxfix; yfix=CONSTANTS.siloyfix;
				goldAmount -= CONSTANTS.siloCost;
				new PopupText(engine, "-"+CONSTANTS.siloCost, 0xE0C000, currentWorkingX, currentWorkingY);
				buildingSprite.pics = siloAn.pics;
				animated = false;
				maxGoldAmount += 500;
				maxFuelAmount += 500;
			}
			spendCoin.play();
			placement.play();
			if(animated) buildingSprite.run();
			else buildingSprite.setSprite();
			buildingSprite.container.mouseEnabled = false;
			buildingSprite.container.mouseChildren = false;
			buildingSprite.moveTo(x*gridWidth+xfix,y*gridWidth+yfix,1);
			var b:Building = engine.giveBuilding(x,y,buildType,buildingSprite,productionRate);		
			if (buildType==CONSTANTS.siloType) silos.push(b);
			
			tempDrag.x=10000;
			trace (x,y);
			cancelBuild.visible=false;
			building=false;
			scene.render();
		}
		private function cancelBuilding(e:Event):void{
			building=false;
			tempDrag.x=10000;
			cancelBuild.visible=false;
		}
		private function buildDragEffect(e:Event):void{
			if (building){
				var pt:Pt = new Pt(e.target.x, e.target.y);
				//trace("ptx="+pt.x+", pty="+pt.y);
				var squareSize:int = gridWidth; // 
				pt = IsoMath.screenToIso(pt);
				var gridX:int = Math.floor( pt.x / squareSize );
				var gridY:int = Math.floor( pt.y / squareSize );
				//if (Math.abs(gridX-dragX)!=1 || Math.abs(gridY-dragY)==1){dragX=gridX;dragY=gridY;return;}
				if (gridX==dragX && gridY==dragY)return;
				dragX=gridX;
				dragY=gridY;
				
				var im:Animation =  new Animation();
				var xfix:int = 0;
				var yfix:int = 0;
				if (buildType==CONSTANTS.garageType){
					xfix=CONSTANTS.garagexfix;yfix=CONSTANTS.garageyfix;
					im.pics = garageAn.pics;
				}
				else if (buildType==CONSTANTS.generatorType){
					xfix=CONSTANTS.generatorxfix;yfix=CONSTANTS.generatoryfix;
					im.pics = powerFarmAn.pics;
				}
				else if (buildType==CONSTANTS.factoryType){
					xfix=CONSTANTS.factoryxfix;yfix=CONSTANTS.factoryyfix;
					im.pics = factoryAn.pics;
				}
				else if (buildType==CONSTANTS.siloType){
					xfix=CONSTANTS.siloxfix;yfix=CONSTANTS.siloyfix;
					im.pics = siloAn.pics;
				}
				var bt:BitmapData = (im.pics[0] as ImageSprite).bitmap;
				var result:BitmapData = bt.clone();
				var blur:GlowFilter = new GlowFilter();
				var my_color:ColorTransform = new ColorTransform();
				
				blur.blurX = 16; 
				blur.blurY = 16; 
				if (engine.canPlace(buildType,gridX,gridY))
					blur.color=0x00FF00;
				else
					blur.color=0xFF0000;
				blur.quality = BitmapFilterQuality.MEDIUM;
				result.applyFilter(result,new
					Rectangle(0,0,bt.width,bt.height),new Point(0,0),blur);
				my_color.alphaMultiplier=0.55;
				result.colorTransform(new
					Rectangle(0,0,bt.width,bt.height),my_color);
				
				tempDrag.sprites = [result];
				tempDrag.container.mouseEnabled = false;
				tempDrag.container.mouseChildren = false;
				
				tempDrag.moveTo(gridX*gridWidth+xfix,gridY*gridWidth+yfix,1);
				scene.addChild(tempDrag);
				scene.render();
			}
		}
		//mouse functions
		private function viewMouseDown(e:Event):void{
			panPt = new Point(stage.mouseX, stage.mouseY);
			view.addEventListener(MouseEvent.MOUSE_MOVE, viewPan);
			view.addEventListener(MouseEvent.MOUSE_UP, viewMouseUp);
		}
		private function viewMouseClick(e:Event):void{
			var pt:Pt = new Pt(e.target.x, e.target.y);
			var squareSize:int = gridWidth; // 
			pt = IsoMath.screenToIso(pt);
			var gridX:int = Math.floor( pt.x / squareSize );
			var gridY:int = Math.floor( pt.y / squareSize );
			trace(gridX,gridY);
			if (gridX<0)return;
			currentWorkingX=gridX;
			currentWorkingY=gridY;
			if (building){
				place(gridX,gridY);
			}
			else{
				var square:String = engine.getType(gridX,gridY);
				if (square==null)return;
				if (square == CONSTANTS.garageType){
					if (!garageMenu.showing)
						garageMenu.showWithResource(engine.getMain(currentWorkingX,currentWorkingY));
					else garageMenu.hide();
				}
				if (square == CONSTANTS.generatorType){
					if (!generatorMenu.showing)
						generatorMenu.showWithResource(engine.getMain(currentWorkingX,currentWorkingY));
					else generatorMenu.hide();
				}
				if(square == CONSTANTS.factoryType){
					if (!factoryMenu.showing)
						factoryMenu.show();
					else
						factoryMenu.hide();
				}
			}
		}
		
		private function dragMouseDown(e:Event):void{
			this.addEventListener(MouseEvent.MOUSE_UP,dragMouseUp);
			zoomblock.startDrag(false,new Rectangle(zoomblock.x,zoomBarY+30,0,zoombar.bitmap.height-80));
			//zoomBarX-10,zoomBarY+(highZoom-lowZoom)*zoom*zoombar.bitmap.height
		}
		private function dragMouseUp(e:Event):void{
			zoomblock.stopDrag();
			this.removeEventListener(MouseEvent.MOUSE_UP, dragMouseUp);
		}
		
		
		private function viewPan(e:Event):void{
			var dragRange:int = 20;
			if (panPt.x>SCR_WID-dragRange || panPt.x<dragRange || panPt.y>SCR_HGT-dragRange || panPt.y<dragRange)return;
			view.panBy((panPt.x - stage.mouseX)/zoom, (panPt.y - stage.mouseY)/zoom);
			panPt.x = stage.mouseX;
			panPt.y = stage.mouseY;
		}
		private function viewMouseUp(e:Event):void{
			view.removeEventListener(MouseEvent.MOUSE_MOVE, viewPan);
			view.removeEventListener(MouseEvent.MOUSE_UP, viewMouseUp);
			
		}
		private function viewZoom(e:MouseEvent):void{
			if(e.delta > 0 && zoom+0.2<highZoom)
			{zoom +=  0.10;}
			if(e.delta < 0 && zoom-0.2>lowZoom) 
			{zoom -=  0.10;}
			view.currentZoom = zoom;
			zoomblock.setPosition(zoomblock.x,(-zoom+highZoom)/(highZoom-lowZoom)*(zoombar.hgt)+zoomBarY-10); 
		}
		private function viewZoomIn(e:MouseEvent):void{
			if(zoom<highZoom)
			{zoom +=  0.10;}
			view.currentZoom = zoom;
		}
		private function viewZoomOut(e:MouseEvent):void{
			if( zoom>lowZoom)
			{zoom -=  0.10;}
			view.currentZoom = zoom;
		}
		private function enterFrameHandler (evt:Event):void
		{
		}
		public function getCars():Array{
			var ar:Array = new Array();
			for (var k:int = 0;k<engine.cars.length;k++){
				if (engine.cars[k]!=null)ar.push((engine.cars[k] as Car));
			}
			return ar;
		}
	}
}
